﻿using PetAdoptApi.Services.Auth;
using PetAdoptApi.Database;
using Microsoft.EntityFrameworkCore;
using PetAdoptApi.Endpoints;
using PetAdoptApi.Utils;
using Microsoft.AspNetCore.Diagnostics;
using static System.Net.Mime.MediaTypeNames;
using PetAdoptApi.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

builder.Services.ConfigureHttpJsonOptions(ops =>
{
    ops.SerializerOptions.Converters.Add(new DateTimeJsonConverters());
});

builder.Services.AddDbContext<AppDbContext>(ops =>
{
    string connectionString = builder.Configuration.GetConnectionString("DefaultConnection")!;
    ops.UseMySql(connectionString, new MySqlServerVersion(new Version(8,0,21)));
#if DEBUG
    ops.LogTo(Console.WriteLine,LogLevel.Information)
    .EnableSensitiveDataLogging()
    .EnableDetailedErrors();
#endif
},ServiceLifetime.Scoped);


builder.Services.AddProblemDetails(ops =>
{
    ops.CustomizeProblemDetails = (ctx) =>
    {
        if(ctx.ProblemDetails.Status == StatusCodes.Status400BadRequest)
        {
            ctx.ProblemDetails.Detail = "this is custon problem detai";
        }
    };
});

builder.Services.AddAuthentication(op =>
{
    op.AddScheme<AuthenticationHandlerImpl>(AuthenticationHandlerImpl.SchemaName, "default scheme");
    op.DefaultScheme = AuthenticationHandlerImpl.SchemaName;
    op.DefaultChallengeScheme = AuthenticationHandlerImpl.SchemaName;
});

builder.Services.AddStackExchangeRedisCache(op => op.Configuration = builder.Configuration.GetConnectionString("RedisConnection"));

builder.Services.AddSingleton<TokenService>();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthentication();
app.UseAuthorization();

app.UseExceptionHandler(ErrorHandler.ConfigExceptionhandler);

app.MapControllers();
app.MapEndpoints();

app.Run();

